import { Component, OnInit, OnDestroy, TemplateRef } from '@angular/core';

import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

import { Term } from '../Interfaces/Term';
import { DateFormatter } from 'ngx-bootstrap/index';

import { BsDatepickerConfig, BsLocaleService } from 'ngx-bootstrap/datepicker';

import { TermService } from '../../services/term.service';
import { error } from 'util';


import * as _ from 'lodash';


@Component({
  selector: 'app-term',
  templateUrl: './term.component.html',
  styleUrls: ['./term.component.css']
})

export class TermComponent implements OnInit, OnDestroy {

  terms: Term[];
  term: Term;
  // 时间空间语言设置
  locale = 'zh-cn';
  // 时间区间
  daterange = Array;
  editDaterange = Array;

  // 操作
  action  = 'none';
  // 提示
  alerts: any = [];
  // 编辑弹出框
  editModalRef: BsModalRef;

  constructor(
    private _localeService: BsLocaleService,
    private termService: TermService,
    private modalService: BsModalService,
  ) {
    this._localeService.use(this.locale);
  }

  ngOnInit() {
    // console.log('init term');
    // this.modalService.onHidden.subscribe(res => { this.getTerms(); } );
    this.term = new Term();
    this.term.status = 1; // 默认可用
    // console.log("lodash version:",_.VERSION);
    this.getTerms();
  }

  ngOnDestroy() {
    // console.log('destory term');
    // this.modalService.onHidden.unsubscribe();
  }

  /**
   * 显示新增区域
   */
showNewModal()
{
    if (this.action == 'new')
        this.action = 'none';
    else
        this.action = 'new';
}

  getTerms() {
    this.termService.getTerms().then(
      res => {
        console.log(res);
        this.terms = res;
      }
    );
  }
  /**
   * 新增学期
   */
  addTerm (term) {
    if (this.daterange.length <= 1) {
      this.showMessage('danger', '请选择时间', 2000);
      return ;
    }
    let format  = new DateFormatter();
    this.term.start_day = format.format(this.daterange[0], 'YYYY-MM-DD', 'en');
    this.term.end_day = format.format(this.daterange[1], 'YYYY-MM-DD', 'en');

    this.termService.addTerm(this.term)
        .subscribe(res => {
          this.alerts.push({
            type: 'info',
            msg: `添加成功`,
            timeout: 2000
          });
          this.terms.splice(0, 0, res.data);
          this.showNewModal();
        });
  }

  showMessage(type:string, message:string,timeout:number)
  {
    this.alerts.push({
      type: type,
      msg: message,
      timeout: timeout
    });
  }

  // 打开编辑弹出框
    openEditModal2(template: TemplateRef<any>, term: Term) {
        this.term = term;
        this.editModalRef = this.modalService.show(template);
    }

    editTerm(term: Term) {
        const format  = new DateFormatter();
        this.term.start_day = format.format(this.editDaterange[0], 'YYYY-MM-DD', 'en');
        this.term.end_day = format.format(this.editDaterange[1], 'YYYY-MM-DD', 'en');
        this.termService.editTerm(this.term)
            .then(res => {
                alert('编辑成功！');
                this.getTerms();
            });
    }

  openEditModal(term: Term) {
    console.log(term);
    term = _.clone(term);
    this.editModalRef = this.modalService.show(EditModalComponent);
    this.editModalRef.content.title = '编辑' ;
    this.editModalRef.content.id = term.id;
    this.editModalRef.content.name = term.name;
    this.editModalRef.content.term = term;
    console.log(this.editModalRef.content);
  }

  // 打开删除弹出框
  removeTerm(term: Term) {
    //   this.editModalRef = this.modalService.show(DeleteModalComponent);
    //   this.editModalRef.content.title = '确认删除么？' ;
    //   this.editModalRef.content.term = term;
    //   this.modalService.onHidden.subscribe(res => { this.getTerms(); } );
    if (confirm('确认删除么?')) {
        this.termService.delete(term).then(res => {
            if (!res.errors) {
                alert('删除成功');
                this.getTerms();
            } else {
                alert('删除失败！');
            }
        });
    }
  }
}


@Component({
    selector: 'app-delete-modal',
    template: `
    <div class="modal-header">
        <h4 class="modal-title pull-left">{{title}}</h4>
        <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
            <span aria-hidden="true">&times;</span>
        </button>
        </div>
        <div class="modal-body">
            <div class="form-group row">
                <div class="col-sm-2">
                    <button type="button" (click)="deleteTerm(term)" class="btn btn-success" >删除</button>
                </div>
            </div>
        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">Close</button>
        </div>
    `
    ,
})
export class DeleteModalComponent {
    title: string;
    term: Term;
    constructor(
        public bsModalRef: BsModalRef,
        private termService: TermService
    ) {
    }

    deleteTerm(term: Term) {
        this.termService.delete(this.term)
        .then(
            res => {
                console.log(res);
            }
        );
    }
}



 // 这个组件的赋值有延时，所以如果是对象传进去，必须加上*ngIf
@Component({
  selector: 'app-edit-modal',
  template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">{{title}}</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <form #editForm="ngForm" (submit)="editTerm(editForm.value)">
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">学期名</label>
            <div class="col-sm-9">
                <input type="text"  *ngIf="term"
                required 
                class="form-control" 
                name="name" 
                [(ngModel)]="term.name" 
                placeholder="如：2018年第一学期"
                value="{{term.name}}"
                #uname="ngModel"
                >
            </div>
        </div>

        <div class="form-group row">
            <label for="daterange" class="col-sm-3 col-form-label">时间区间</label>
            <div class="col-sm-9">
                <input placeholder="学期开始时间~结束时间" readonly 
                #urange="ngModel"
                type="text"
                class="form-control"
                name="daterange"
                [(ngModel)]="daterange"
                bsDaterangepicker
                #dpr="bsDaterangepicker" />
            </div>
        </div>
        <div class="form-group row">
            <div class="col-sm-2">
                <button type="submit" [disabled]="!editForm.form.valid" class="btn btn-success" >保存</button>
            </div>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">Close</button>
    </div>
  `
})
export class EditModalComponent {
    title: string;
    term: Term;
    daterange: Date[];
    constructor(
        public bsModalRef: BsModalRef,
        private termService: TermService
    ) {
        setTimeout(()=>{
                this.daterange = [
                    new Date(this.term.start_day),
                    new Date(this.term.end_day)
                ];
        },500);
    }

    editTerm(term: Term) {
        const format  = new DateFormatter();
        this.term.start_day = format.format(this.daterange[0],'YYYY-MM-DD','en');
        this.term.end_day = format.format(this.daterange[1],'YYYY-MM-DD','en');
        this.termService.editTerm(this.term)
            .then(res=>{
                alert("编辑成功！");
            });
    }
}

